from uuid import uuid1

from info_collect import db
from info_collect.models import Classroom
from info_collect.models import obj_to_dict


def add_classroom(body):
    """
    Add a new classroom
    
    :param body: Classroom object that needs to be added to the store
    :type body: dict | bytes

    :rtype: Classroom
    """
    id = unicode(uuid1())
    name = body.get('name')
    desc = body.get('description')
    c = Classroom(id, name, desc)
    db.session.add(c)
    db.session.commit()

    return obj_to_dict(c)


def delete_classroom(classroomId):
    """
    Deletes a classroom
    
    :param classroomId: ID of classroom
    :type classroomId: int

    :rtype: None
    """
    c = Classroom.query.get(classroomId)
    db.session.delete(c)
    db.session.commit()
    return obj_to_dict(c)


def get_classroom(classroomId):
    """
    Find classroom by ID
    
    :param classroomId: ID of classroom
    :type classroomId: int

    :rtype: Classroom
    """

    c = Classroom.query.get(classroomId)
    return obj_to_dict(c)


def list_classroom():
    """
    List classrooms
    

    :rtype: List[Classroom]
    """

    cl = Classroom.query.all()
    return [obj_to_dict(c) for c in cl]


def update_classroom(classroomId, body):
    """
    Update an existing classroom
    
    :param classroomId: ID of classroom
    :type classroomId: int
    :param body: Classroom object that needs to be added to the store
    :type body: dict | bytes

    :rtype: Classroom
    """
    c = Classroom.query.get(classroomId)
    for k in body:
        setattr(c, k, body[k])
    db.session.commit()
    return obj_to_dict(c)
